#!/usr/bin/env python
# coding: utf-8

from rediscluster import client
debug_mode = True
class RedisClusterClient(object):  # 连接redis集群

    instance = None

    def __init__(self,conn_list):
        self.conn_list = conn_list  # 连接列表
        RedisClusterClient.instance = self.connect()

    def connect(self):
        """
        连接redis集群
        :return: object
        """
        try:
            # 非密码连接redis集群
            # redisconn = StrictRedisCluster(startup_nodes=self.conn_list)
            # 使用密码连接redis集群
            redisconn = client.RedisCluster(startup_nodes=self.conn_list)
            return redisconn
        except Exception as e:
            print(e)
            print("错误,连接redis 集群失败")
            return False

    def get_state(self):
        """
        获取状态
        :return:
        """
        # res = RedisClusterClient(self.conn_list).connect()
        res = RedisClusterClient.instance
        # print("连接集群对象",res,type(res),res.__dict__)
        if not res:
            return False

        dic = res.cluster_info()  # 查看info信息, 返回dict

        for i in dic:  # 遍历dict
            ip = i.split(":")[0]
            if dic[i].get('cluster_state'):  # 获取状态
                print("节点状态, ip: ", ip, "value: ", dic[i].get('cluster_state'))

    def get_cop_num(self, user_id):
        b_show_num_dict = RedisClusterClient.instance.hgetall("copShowNumMap:" + user_id)
        if debug_mode:
            for k in b_show_num_dict.keys():
                print(k.decode('utf-8') + " : " + b_show_num_dict[k].decode('utf-8') + "\n")

    def get_last_call_info(self, key):
        b_last_call_info_dict = RedisClusterClient.instance.hgetall(key)
        if debug_mode:
            for k in b_last_call_info_dict.keys():
                print(k.decode('utf-8') + " : " + b_last_call_info_dict[k].decode('utf-8') + "\n")
                if b_last_call_info_dict[k] is dict:
                    for kk in b_last_call_info_dict[k].keys():
                        print(kk.decode('utf-8') + " : " + b_last_call_info_dict[k][kk].decode('utf-8') + "\n")

redis_basis_conn = [
            {'host': '172.16.200.35', 'port': 6379},
            {'host': '172.16.200.36', 'port': 6379},
            {'host': '172.16.200.37', 'port': 6379},
            {'host': '172.16.200.38', 'port': 6379},
            {'host': '172.16.200.39', 'port': 6379},
            {'host': '172.16.200.40', 'port': 6379}
        ]

rdc = RedisClusterClient(redis_basis_conn)

# rdc.get_state()